package com.letv.android.client.webview;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.letv.ads.util.ApkDownloadAsyncTask;
import com.letv.android.client.parser.AlbumNewParse;
import com.letv.android.client.utils.AlbumLaunchUtils;
import com.letv.android.client.utils.UIs;
import com.letv.android.client.view.LoadingDialog;
import com.letv.android.young.client.R;
import com.letv.core.api.LetvRequest;
import com.letv.core.api.MediaAssetApi;
import com.letv.core.bean.AlbumNew;
import com.letv.core.bean.DataHull;
import com.letv.core.bean.TopicDetailInfoListBean;
import com.letv.core.constant.PlayConstant;
import com.letv.core.network.volley.VolleyRequest;
import com.letv.core.network.volley.VolleyResponse;
import com.letv.core.network.volley.listener.OnPreExecuteListener;
import com.letv.core.network.volley.toolbox.SimpleResponse;
import com.letv.core.network.volley.toolbox.VolleyNoCache;
import com.letv.core.utils.LetvUtils;
import com.letv.core.utils.LogInfo;
import com.ledim.utils.ToastUtil;
import java.net.URISyntaxException;

public class LetvWebViewActivity extends LetvBaseWebViewActivity implements OnClickListener {

    private WebView mWebView;
    private int jumpType = 0;
    private boolean firstLoad = true;
    private static String titles = "";
    private LoadingDialog mLoadingDialog;
    public static final int M_DEALBACK = 10001;
    private boolean mIsLoading = true;

    /**
     * 调起h5页
     *
     * @param activity
     * @param url
     */
    public static void launch(final Activity activity, String url,
                              final boolean forcedOpenWithWebview, boolean finishSelf, int from) {
        url = url.replaceAll(" ", "");
        if (url != null) {
            if (!(url.startsWith("http://") || url.startsWith("https://"))) {
                url = "http://" + url;
            }
        }
        final String tmp_url = url;

        Intent intent = new Intent(activity, LetvWebViewActivity.class);
        intent.putExtra("url", tmp_url);
        intent.putExtra("from", from == -1 ? PlayConstant.LAUNCH_FROM_MSITE : from);
        if (forcedOpenWithWebview || !launchWebJudgeUrl(activity, tmp_url)) {
            if (finishSelf) {
                activity.finish();
            }
            activity.startActivity(intent);
        }
    }

    public static void launch(final Context context, String url, final String title) {
        boolean isInnerUrl = LetvUtils.judgeInnerUrl(url);
        url = url.replaceAll(" ", "");
        if (url != null) {
            if (!(url.startsWith("http://") || url.startsWith("https://"))) {
                url = "http://" + url;
            }
        }
        titles = title;
        final String tmp_url = url;
        if (!isInnerUrl) {
            Intent intent = new Intent(context, LetvWebViewActivity.class);
            intent.putExtra("url", tmp_url);
            intent.putExtra("loadType", title);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            if (!(context instanceof Activity)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            if (!launchWebJudgeUrl(context, tmp_url)) {
                context.startActivity(intent);
            }
        } else {
            Intent intent = new Intent(context, LetvWebViewActivity.class);
            intent.putExtra("url", tmp_url);
            intent.putExtra("loadType", title);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            if (!(context instanceof Activity)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            if (!launchWebJudgeUrl(context, tmp_url)) {
                context.startActivity(intent);
            }
        }
    }

    public static void launch(final Context context, String url, final String title,
                              final int jumpType) {
        boolean isInnerUrl = LetvUtils.judgeInnerUrl(url);
        url = url.replaceAll(" ", "");
        url = url.replaceAll(" ", "");
        if (url != null) {
            if (!(url.startsWith("http://") || url.startsWith("https://"))) {
                url = "http://" + url;
            }
        }
        final String tmp_url = url;
        if (!isInnerUrl) {
            Intent intent = new Intent(context, LetvWebViewActivity.class);
            intent.putExtra("url", tmp_url);
            intent.putExtra("loadType", title);
            intent.putExtra("jumpType", jumpType);
            if (!launchWebJudgeUrl(context, tmp_url)) {
                context.startActivity(intent);
            }
        } else {
            Intent intent = new Intent(context, LetvWebViewActivity.class);
            intent.putExtra("url", tmp_url);
            intent.putExtra("loadType", title);
            intent.putExtra("jumpType", jumpType);
            if (!launchWebJudgeUrl(context, tmp_url)) {
                context.startActivity(intent);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LogInfo.log("lxx", "LetvWebViewActivity onCreate");
        setNeedStatistics(true);
        super.onCreate(savedInstanceState);
        mWebView = getWebView();
        if (!TextUtils.isEmpty(loadType) && loadType.equals("乐视服务使用协议")) {
            mWebView.getSettings().setJavaScriptEnabled(false);
        } else {
            mWebView.getSettings().setJavaScriptEnabled(true);
        }
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition,
                                        String mimetype, long contentLength) {
                LogInfo.log("LXF", loadType + "<<-----------download url------------>>" + url);
                LogInfo.log("lxx", "DownloadListener,url: " + url + ",userAgent: " + userAgent +
                        ",mimetype: " + mimetype + ",contentDisposition: " + contentDisposition +
                        ",contentLength: " + contentLength);
                ApkDownloadAsyncTask.downloadApk(LetvWebViewActivity.this, url, loadType);
                LetvWebViewActivity.this.finish();
            }
        });
        mWebView.setWebViewClient(new LetvWebViewClient());
    }

    /**
     * 进入webView之前判断 url 是不是可以播放
     *
     * @param url
     * @param context
     * @return
     */
    public static boolean launchWebJudgeUrl(Context context, String url) {
        if (!TextUtils.isEmpty(url) && url.toLowerCase().contains("vplay_")) {
            int index = url.lastIndexOf("/");
            if (index > 0) {
                String u = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
                if (u.contains("vplay_")) {
                    String vplayId = u.substring(u.lastIndexOf("_") + 1, u.length());
                    if (!TextUtils.isEmpty(vplayId)) {
                        requestAlbum(vplayId, context);
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    protected String setBaseUrl() {
        return null;
    }

    private class LetvWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, String url) {
            if (url.startsWith("intent://")) {
                try {
                    Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                    LetvWebViewActivity.this.startActivity(intent);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                    LogInfo.log("wlx", e.getMessage());
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                    LogInfo.log("wlx", e.getMessage());
                }
                return true;
            }
            LetvWebViewActivity.this.urlTitleView.setText(
                    "由  " + LetvWebViewActivity.this.getUrlTitle(url) + " 提供");
            LetvWebViewActivity.this.pullDownUrlText.setText(
                    "由  " + LetvWebViewActivity.this.getUrlTitle(url) + " 提供");
            LogInfo.log("+-->", "LetvWebViewActivity---------------->>>>>>>>>>>>>");
            String last_should_url = "";
            try {
                if (firstLoad) {
                    firstLoad = false;
                }
                LogInfo.log("haitian", "topicWeb" + "url = " + url);
                if (url.toLowerCase().contains("vplay_")) {
                    int index = url.lastIndexOf("/");
                    if (index > 0) {
                        String u = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
                        if (u.contains("vplay_")) {
                            String vplayId = u.substring(u.lastIndexOf("_") + 1, u.length());
                            if (!isFinish && !TextUtils.isEmpty(vplayId)) {
                                view.stopLoading();
                                requestAlbum(vplayId, mActivity);
                                return true;
                            }
                        }
                    }
                } else {
                    int index = url.indexOf("?");
                    if (index > 0 || !LetvUtils.judgeInnerUrl(url)) {////或者来自外网,外网有没?&&后缀情况
                        String u = null;
                        if (url.contains("vtype=mp4")) {
                            jumpType = 0;
                        } else if (url.contains("zid=")) {
                            jumpType = 1;
                        }
                        if (index > 0) {
                            if (jumpType == 1) {
                                u = url.substring(url.indexOf("?") + 1);
                            } else {
                                u = url.substring(0, url.indexOf("?"));
                            }
                        }
                        if (!TextUtils.isEmpty(u) || !LetvUtils.judgeInnerUrl(url)) {
                            LogInfo.log("clf", "jumpType == 0");
                            if (jumpType == 0) {
                                if (index > 0 &&
                                        ".mp4".equals(u.substring(u.lastIndexOf("."), u.length())) &&
                                        url.contains("vtype=mp4")) {
                                    view.stopLoading();
                                    if (!isFinish) {
                                        final String temp_url = url;
                                        Intent intent = new Intent(Intent.ACTION_VIEW);
                                        String type = "video/mp4";
                                        Uri name = Uri.parse(temp_url);
                                        intent.setDataAndType(name, type);
                                        intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                                        LetvWebViewActivity.this.startActivity(intent);
                                    }
                                    return false;
                                }
                            } else if (jumpType == 1) {
                                view.stopLoading();
                                u = u.toLowerCase();
                                if (u.contains("zid=")) {
                                    requestTopicPlay(u);
                                    return true;
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

                LogInfo.log("lxx", "5555");
                last_should_url = url;
            }

            return super.shouldOverrideUrlLoading(view, url);
        }

        /**
         * 请求专题信息
         *
         * @param userInfo
         */
        private void requestTopicPlay(String userInfo) {

            String[] uSpilts = userInfo.split("&");
            String vid = null;
            String pid = null;
            String zid = null;
            for (String item : uSpilts) {
                if (item.contains("=")) {
                    if (item.contains("zid")) {
                        zid = item.substring(item.indexOf("=") + 1);
                    } else if (item.contains("pid")) {
                        pid = item.substring(item.indexOf("=") + 1);
                    } else if (item.contains("vid")) {
                        vid = item.substring(item.indexOf("=") + 1);
                    }
                }
            }

            if (TextUtils.isEmpty(zid)) {
                ToastUtil.toast(R.string.topic_player_info);
                return;
            }
            final String finalZid = zid;
            final String finalPid = pid;
            final String finalVid = vid;
            new LetvRequest<TopicDetailInfoListBean.TopicDetailInfoBean>(getActivity(), TopicDetailInfoListBean.TopicDetailInfoBean.class)
                    .setOnPreExecuteListener(new OnPreExecuteListener() {
                        @Override
                        public boolean onPreExecute() {
                            showDialog();
                            return true;
                        }
                    })
                    .setUrl(MediaAssetApi.getInstance().getTopicDeatil(mContext, zid, null))
                    .setCache(new VolleyNoCache())
                    .setCallback(new SimpleResponse<TopicDetailInfoListBean.TopicDetailInfoBean>() {
                        @Override
                        public void onNetworkResponse(
                                VolleyRequest<TopicDetailInfoListBean.TopicDetailInfoBean> request,
                                TopicDetailInfoListBean.TopicDetailInfoBean result, DataHull hull,
                                VolleyResponse.NetworkResponseState state) {
                            LogInfo.log(getActivityName() + "||wlx", "state=" + state);
                            if (state == VolleyResponse.NetworkResponseState.SUCCESS) {
                                toTopic(result, finalZid, finalPid, finalVid);
                            } else {
                                cancelDialog();
                                ToastUtil.toast(R.string.net_no);
                            }
                        }
                    })
                    .add();

        }

        /**
         * 跳转到专题
         *
         * @param topicInfo
         */
        private void toTopic(TopicDetailInfoListBean.TopicDetailInfoBean topicInfo, String zid,
                             String pid, String vid) {
            cancelDialog();
            if (topicInfo == null || topicInfo.getSubject() == null) {
                return;
            }
            LogInfo.log(
                    getActivityName() + "||wlx",
                    "type = " + topicInfo.getSubject().getType() + " zid =" + Long.parseLong(zid) +
                            " pid =" + Long.parseLong(pid) + " vid =" + Long.parseLong(vid));
            AlbumLaunchUtils.launchTopic(mActivity, Long.parseLong(zid), Long.parseLong(pid), Long.parseLong(vid), topicInfo
                    .getSubject()
                    .getType(), PlayConstant.LAUNCH_FROM_ATTENDANCE_WEB);
        }

        private void showDialog() {
            LogInfo.log(getActivityName() + "||wlx", "showDialog");
            if (mLoadingDialog == null || !mLoadingDialog.isShowing()) {
                if (!(mActivity.isFinishing() && !mActivity.isRestricted())) {
                    try {
                        mLoadingDialog = new LoadingDialog(mActivity, R.string.dialog_loading);
                        mLoadingDialog.setCancelable(true);
                        mLoadingDialog.show();
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        private void cancelDialog() {
            if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
                try {
                    mLoadingDialog.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            LogInfo.log("LM", "onReceivedSslError");
            handler.proceed();  //ssl证书认证错误处理
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mIsLoading = true;
            LogInfo.log("wlx", "onPageStart");
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mIsLoading = false;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description,
                                    String failingUrl) {
            LogInfo.log("lxx",
                    "errorCode: " + errorCode + ",description: " + description + ",failingUrl: " +
                            failingUrl);
            if (errorCode != -10) {
                flag = false;
                root.netError(false);
                urlTitleView.setVisibility(View.GONE);
                progressBar.setVisibility(View.GONE);
                mWebView.setNetworkAvailable(true);
            }
        }
    }

    @Override
    public boolean isLoading() {
        return mIsLoading;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if (id == R.id.back_iv) {
            //if (!TextUtils.isEmpty(loadType) &&
            //        loadType.equals(getResources().getString(R.string.letv_search_name))) {
            //    StringBuilder sb = new StringBuilder();
            //    sb.append(DataConstant.StaticticsVersion2Constatnt.StaticticsName.STATICTICS_NAM_PAGE_ID)
            //      .append(PageIdConstant.searchResultPage);
            //    sb.append(DataConstant.StaticticsVersion2Constatnt.StaticticsName.STATICTICS_NAM_FL)
            //      .append("d21");
            //    sb.append(DataConstant.StaticticsVersion2Constatnt.StaticticsName.STATICTICS_NAM_WZ)
            //      .append("1");
            //    DataStatistics.getInstance()
            //                  .sendActionInfo(LetvWebViewActivity.this, "0", "0", LetvConfig.getPcode(this), "0", sb
            //                                  .toString(), "0", null, null, null, LetvUtils.getUID(), null, null, null, null,
            //                          PreferencesManager.getInstance().isLogin() ? 0 : 1, null);
            //}
            UIs.hideSoftkeyboard(this);
            if (mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                finish();
            }

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (!TextUtils.isEmpty(titles) && titles.equals("抢兑")) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    mWebView.reload();
                }
            }, 1000);
        }
    }

    /**
     * 请求专辑详情
     */
    private static void requestAlbum(final String vid, final Context context) {
        String url = MediaAssetApi.getInstance().requestGetAlbumByIdUrl(context, vid);
        new LetvRequest<AlbumNew>(context, AlbumNew.class).setUrl(url)
                                                          .setParser(new AlbumNewParse())
                                                          .setCache(new VolleyNoCache())
                                                          .setCallback(new SimpleResponse<AlbumNew>() {
                                                              @Override
                                                              public void onNetworkResponse(
                                                                      VolleyRequest<AlbumNew> request,
                                                                      AlbumNew result,
                                                                      DataHull hull,
                                                                      VolleyResponse.NetworkResponseState state) {
                                                                  if (state ==
                                                                          VolleyResponse.NetworkResponseState.SUCCESS) {
                                                                      LogInfo.log("LetvWebviewActivity||wlx", "播放视频");
                                                                      if (result.getType() ==
                                                                              AlbumNew.Type.VRS_MANG) {
                                                                          AlbumLaunchUtils.launch(context, result
                                                                                  .getId(), Long.parseLong(vid), 0, null);
                                                                      } else {
                                                                          AlbumLaunchUtils.launch(context, 0, Long
                                                                                  .parseLong(vid), 0, null);
                                                                      }
                                                                  } else {
                                                                      onError(state, context);
                                                                  }
                                                              }
                                                          })
                                                          .add();
    }

    /**
     * 错误提示
     *
     * @param state
     * @param context
     */
    private static void onError(VolleyResponse.NetworkResponseState state, Context context) {
        switch (state) {
            case NETWORK_NOT_AVAILABLE:
            case NETWORK_ERROR:
                ToastUtil.toast(R.string.net_no);
                break;
            case RESULT_ERROR:
                ToastUtil.toast(R.string.get_data_error);
                break;
            default:
                break;
        }
    }
}
